const conn = require('../db/db.js');

const showIndexPage = (req,res) => {

    let pageSize = 3;
    let nowPage = parseInt(req.query.page) || 1;
    let offset = (nowPage - 1) * pageSize;

    let sql =  `SELECT a.id,a.title,a.ctime,u.nickname FROM blog_articles a
                LEFT JOIN blog_users u ON u.id = a.authorId
                ORDER BY a.ctime DESC
                LIMIT ${offset},${pageSize}; 
                SELECT count(*) as count FROM blog_articles`;
    conn.query(sql,(err,result) => {
        let totalPage = Math.ceil(result[1][0].count / pageSize);
        if(err) return res.send({status:501,msg:'查询失败' + err.message});
        // 填入session中的值放入到Index.esj中渲染
        res.render('index.ejs',{
            user:req.session.user,
            islogin:req.session.islogin,
            articles:result[0],
            totalPage:totalPage,
            nowPage:nowPage
        });
    })   
};

module.exports = {
    showIndexPage
}